// server/api/studies/index.post.ts
import { defineEventHandler, readBody } from 'h3'
import { verifyToken } from '../../utils/auth'
import prisma from '../../utils/prisma'

export default defineEventHandler(async (event) => {
  try {
    console.log('收到创建学习记录请求')
    
    // 1. 验证认证
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw createError({
        statusCode: 401,
        statusMessage: '未提供认证令牌'
      })
    }
    
    const token = authHeader.slice(7)
    const decoded = verifyToken(token)
    if (!decoded) {
      throw createError({
        statusCode: 401,
        statusMessage: '令牌无效或已过期'
      })
    }
    
    // 2. 读取请求体
    const body = await readBody(event)
    console.log('请求体:', body)
    
    const { username, content, type, applicationScenario, interviewFrequency, remark } = body
    
    // 3. 验证必填字段
    if (!username) {
      throw createError({
        statusCode: 400,
        statusMessage: '需要提供用户名'
      })
    }
    
    if (!content || !type || !applicationScenario) {
      throw createError({
        statusCode: 400,
        statusMessage: '学习内容、学习类型和应用场景为必填项'
      })
    }
    
    // 4. 查找用户
    const user = await prisma.user.findUnique({
      where: { username }
    })
    
    if (!user) {
      throw createError({
        statusCode: 404,
        statusMessage: '用户不存在'
      })
    }
    
    console.log('找到用户:', user.id, user.username)
    
    // 5. 创建学习记录
    const study = await prisma.study.create({
      data: {
        content,
        type,
        applicationScenario,
        interviewFrequency: interviewFrequency ? parseInt(interviewFrequency) : null,
        remark: remark || null,
        userId: user.id
      }
    })
    
    console.log('学习记录创建成功, ID:', study.id)
    
    // 6. 返回成功响应
    return {
      code: 201,
      message: '学习记录创建成功',
      data: study
    }
    
  } catch (error: any) {
    console.error('创建学习记录失败:', error)
    
    // 返回具体的错误信息
    return {
      code: error.statusCode || 500,
      message: error.message || '服务器内部错误',
      error: process.env.NODE_ENV === 'development' ? error.stack : undefined
    }
  }
})